<template>
  <m-container class="detail">
    <in-work-top-cell :info="info" />
    <m-cell-group size="sm" v-if="getIsOver" v-for="(item, index) in info.stockInWorkList" :key="index">
      <m-cell title="入库明细" weight="title" :border="false" />
      <view class="box" style="padding-top: 0; margin-top: -15rpx">
        <view class="item">
          <text class="title">托盘编号</text>
          <text>{{ item.palletCode }}</text>
        </view>
        <view class="item">
          <text class="title">派送方式</text>
          <text>{{ deliveryTypeMap[item.deliveryType] }}</text>
        </view>
        <view class="item">
          <text class="title">当前站点</text>
          <text>{{ item.deliveryStartCode }}</text>
        </view>
        <view class="item">
          <text class="title">目标站点</text>
          <text>{{ item.deliveryTargetCode }}</text>
        </view>
      </view>
    </m-cell-group>

    <u-checkbox-group shape="circle" v-if="info.imsStockInOrderDetailList.length">
      <m-cell-group
        v-for="(item, index) in info.imsStockInOrderDetailList"
        :key="index + '_' + (item.palletCodeSkuList || []).length"
      >
        <view class="box">
          <view @click="hanldeItemClick(index)">
            <view class="df aic jcsb">
              <m-tag>{{ item.skuName }}</m-tag>
              <u-checkbox :value="item.checked" :disabled="getItemDisabled(item)" v-if="getIsShowCheckbox">
              </u-checkbox>
            </view>
            <view class="item">
              <text class="title">SKU编号</text>
              <text>{{ item.skuCode }}</text>
            </view>
            <view class="item">
              <text class="title">零件图号</text>
              <text>{{ item.skuPartNo }}</text>
            </view>
            <view class="df aic jcsb">
              <view class="item">
                <text class="title">包装数量</text>
                <text>{{ item.realPackageNumber }}</text>
              </view>
              <view class="item">
                <text class="title">入库数量</text>
                <text>{{ item.packageQuantity }}</text>
              </view>
            </view>
            <view class="item">
              <text class="title">分拣数量</text>
              <text>{{ (item.palletCodeSkuList || []).length }}</text>
            </view>
          </view>

          <view class="footer">
            <m-button
              plain
              size="md"
              shape="round"
              :width="getShwowPrintCode(item) ? '46%' : '90%'"
              @click="handleClickScan(item)"
              :disabled="getScanButtonDisabled(item)"
              background="#fff"
            >
              {{ getShowBtn ? '扫码入库' : '入库详情' }}
            </m-button>
            <m-button
              type="primary"
              size="md"
              shape="round"
              width="46%"
              @click="handleClickPrint(item)"
              v-if="getShwowPrintCode(item)"
            >
              打印条码
            </m-button>
          </view>
        </view>
      </m-cell-group>
    </u-checkbox-group>
    <m-empty v-else />

    <m-fixed v-if="getShowBtn">
      <m-button width="100%" size="xl" @click="handleClickStartIn" :disabled="!getDisabled">开始入库</m-button>
    </m-fixed>
  </m-container>
</template>

<script>
import { router } from '@/router'
import {
  getWorkOrder,
  InWorkHistoryDetail,
  getCurrentPalletCode,
  barcodeRecordList,
  existAreaOfSkuIds,
} from '@/api/modules/in-work'
import { map } from '@/utils/constant'
import { mapState } from 'vuex'
import { deliveryTypeMap } from '@/utils/constant'
import { showModal } from '@/hooks'

export default {
  data() {
    return {
      options: {
        type: 'fastInWork',
      },
      map,
      deliveryTypeMap,
      isOver: null,
    }
  },
  computed: {
    ...mapState({
      info: (state) => state.inWork.info,
      scanInOrderDetailId: (state) => state.inWork.scanInOrderDetailId,
    }),
    getShowBtn() {
      const { status, pickStatus, sourceType } = this.info
      // 入库中拣货完成
      if (status === 2 && pickStatus === 2) {
        return false
      }
      return ![2, 3].includes(status) && sourceType === 0
    },
    getShwowPrintCode() {
      return (item) => item.needPrintBarcode === 1 && ![2, 3].includes(this.info.status)
    },
    getScanButtonDisabled() {
      return (item) => {
        if (this.getIsSystem) {
          return this.info.status === 2 ? false : !(!this.getItemDisabled(item) && item.checked === true)
        }
        return false
      }
    },
    getItemDisabled() {
      return (item) => {
        if (item.status === 2) {
          return true
        }

        const arr = this.info.imsStockInOrderDetailList.filter((item) => item.checked)
        if (arr.length) {
          const { imsId } = arr[0]
          return item.imsId !== imsId
        }
        return false
      }
    },
    getDisabled() {
      const { imsStockInOrderDetailList: list, pickStatus } = this.info

      if (this.getIsSystem) {
        const arr = list.filter((item) => item.checked)
        const isEmpty = arr.filter((item) => {
          const data = (item.palletCodeSkuList || []).filter((item) => {
            if (typeof item === 'string' || item.status === 0) {
              return true
            }
            return false
          })
          return data.length !== 0
        })

        if (arr.length !== 0 && arr.length === isEmpty.length) {
          return true
        }

        if (this.isOver === '' && pickStatus === 2) {
          return false
        }

        return arr.length ? arr.every((item) => this.scanInOrderDetailId.includes(item.inOrderDetailId)) : false
      }

      return list.every((item) => this.scanInOrderDetailId.includes(item.inOrderDetailId))
    },
    getIsSystem() {
      return this.options.type === 'systemInWork'
    },
    getIsShowCheckbox() {
      if (this.getIsSystem) {
        if (this.info.status === 2) {
          return !(this.info.pickStatus === 2)
        }
        return [1, 4].includes(this.info.status)
      }
      return false
    },
    getIsOver() {
      const { status, pickStatus } = this.info
      if ([1, 2, 4].includes(status)) {
        if (status === 2) {
          return true
        }

        return status === 4 && pickStatus === 2
      }
      return false
    },
  },
  async onLoad(options) {
    this.options = options
    this.$store.commit('inWork/setClearScanInOrderDetailId')
    this.fetchData()
  },
  onUnload() {
    this.$store.commit('inWork/setClearScanInOrderDetailId')
  },
  onShow() {
    if (!this.getIsSystem) {
      this.fetchData()
    }
  },
  methods: {
    getTotalWeight() {
      const list = this.info.imsStockInOrderDetailList.filter((item) => item.checked)
      const total = list.reduce((pre, curr) => {
        pre += curr.packageQuantity * curr.grossWeight
        return pre
      }, 0)

      return {
        unitWeight: list.length ? list[0].unitWeight : null,
        total,
      }
    },
    async hanldeItemClick(index) {
      if (!this.getIsShowCheckbox) {
        return
      }

      const item = this.info.imsStockInOrderDetailList[index]
      const bool = this.getItemDisabled(item)

      if (bool) {
        uni.showToast({
          title: item.status === 2 ? '该SKU已完成入库' : '非同一仓库的SKU，不允许同时进行入库操作',
          icon: 'none',
        })
        return
      }

      const list = this.info.imsStockInOrderDetailList.filter((item) => item.checked)

      await existAreaOfSkuIds({
        imsId: list.length ? list[0].imsId : item.imsId,
        skuIds: (list.length ? [...list, item] : [item]).map((item) => item.skuId),
      })

      if (list.length === 0) {
        item.checked = !item.checked
        this.$set(this.info.imsStockInOrderDetailList, index, item)
        return
      }

      const { unitWeight, total } = this.getTotalWeight()
      const isCludes = list.filter((it) => it.skuId === item.skuid)
      if (unitWeight !== null && isCludes.length < 0 && unitWeight < total + item.packageQuantity * item.grossWeight) {
        showModal({
          title: '超重提示',
          content: '无需继续选择（因为已选择的SKU和该SKU的总重量已达到托盘承重最大值了），请您开始入库操作吧！',
          showCancelButton: true,
          confirmText: '开始入库',
          confirm: () => {
            this.handleClickStartIn()
          },
        })
        return
      }

      item.checked = !item.checked
      this.$set(this.info.imsStockInOrderDetailList, index, item)
    },
    async fetchData() {
      const api = {
        history: InWorkHistoryDetail,
        default: getWorkOrder,
      }
      const { data } = await api[this.options.api](this.options.inOrderId)
      data.imsStockInOrderDetailList = data.imsStockInOrderDetailList.map((item) => ({
        ...item,
        checked: false,
      }))
      if (data.imsStockInOrderDetailList.length === 1) {
        data.imsStockInOrderDetailList[0].checked = true
      }

      this.$store.commit('inWork/setInfo', {
        imsStockInOrderDetailList: [],
      })
      this.$store.commit('inWork/setInfo', data)

      if (this.getIsSystem) {
        this.isOver = await getCurrentPalletCode({ inOrderId: this.options.inOrderId })
      }
    },
    handleClickStartIn() {
      this.$store.commit('inWork/setInfo', this.info)
      router.replace({
        name: 'StartIn',
        params: {
          type: this.options.type,
        },
      })
    },
    async handleClickScan(item) {
      if (this.getShwowPrintCode(item)) {
        const { rows } = await barcodeRecordList({
          inOrderDetailId: item.inOrderDetailId,
        })

        if (rows.length === 0) {
          uni.showToast({
            title: '您还没有开始打印条码，不能进行扫码入库操作哦',
            icon: 'none',
          })
          return
        }
      }

      router.push({
        name: 'ScanDetail',
        params: {
          inOrderDetailId: item.inOrderDetailId,
          back: 1,
          type: this.options.type,
        },
      })
    },
    handleClickPrint({ inOrderDetailId }) {
      router.push({
        name: 'PrintCode',
        params: {
          inOrderDetailId,
          type: this.options.type,
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.detail {
  .box {
    padding: 20rpx 0;
    .item {
      display: flex;
      color: #333;
      font-size: 30rpx;
      padding: 15rpx 20rpx 0rpx;
      flex: 1;
      .title {
        color: #70838c;
        width: 180rpx;
        font-size: 26rpx;
      }
    }
    .footer {
      border-top: 1px solid #f5f5f5;
      display: flex;
      justify-content: space-around;
      margin-top: 20rpx;
      padding-top: 20rpx;
    }
  }
  .u-checkbox-group {
    display: block;
  }
}
</style>
